package com.enjoyor.soa.traffic.restt.tpcms.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.enjoyor.soa.traffic.api.dto.tpcms.InfoWhiteListDto;
import com.enjoyor.soa.traffic.api.ubms.dto.VehicleDicDto;
import com.enjoyor.soa.traffic.frame.annotation.Auth;
import com.enjoyor.soa.traffic.frame.security.bean.dto.UserDto;
import com.enjoyor.soa.traffic.restt.tpcms.dubbo.IWhiteListConsumeService;
import com.enjoyor.soa.traffic.restt.tpcms.dubbo.invoke.UbmsDicServiceInvoke;
import com.enjoyor.soa.traffic.util.bean.base.BaseResult;
import com.enjoyor.soa.traffic.util.enums.EnumAppCode;
import com.enjoyor.soa.traffic.util.helper.ExcelToListHelp;
import com.enjoyor.soa.traffic.util.helper.FileToStreamHelp;
import com.enjoyor.soa.traffic.util.helper.ResultHelper;
import com.enjoyor.soa.traffic.util.pojo.ResultPojo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 读取Excel批量新增新增白名单
 * 
 * @author fzj
 * @param fileUrl
 * @param 2018-04-28
 * @return
 */
@Auth
@RestController
@RequestMapping({ "/readExcel" })
@Api("读取excel文件Controller")
@CrossOrigin
public class ReadExcelController {
    /*
     * @Autowired FtpUploadConfig ftpUploadConfig;
     */

    @Autowired
    private IWhiteListConsumeService whiteListConsumeService;

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @PostMapping(value = { "/insertWhiteBatch" }, produces = { "application/json; charset=UTF-8" })
    @ResponseBody
    @ApiOperation(value = "根据路径读取Excel文件", notes = "获取Excel内容批量新增白名单")
    public ResultPojo insertWhiteBatch(@RequestParam String fileUrl, HttpServletRequest request) {
        System.out.println(
                "========================================================================================================"
                        + fileUrl);
        try {
            // ftp://test:test@192.168.56.8:21//tpcmsUpload/20180508//20180508182429394.xlsx;
            InputStream inputStream = FileToStreamHelp.getFile(fileUrl);
            String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
            if (fileName == null || "".equals(fileName)) {
                ResultPojo result = new ResultPojo();
                result = ResultHelper.getResult("文件为空");
                return result;
            }
            // 读取Excel数据到List中
            List<ArrayList<String>> list = ExcelToListHelp.readExcel(fileName, inputStream);
            System.out.println("表格读取完成");
            // 去除列表中的空白行
            list = deleteBlankRow(list);
            System.out.println("表格读取后的列表数据" + list.toString());
            // 检验标题是否为目标文件标题
            boolean flag = checkTitle(list);
            System.out.println("标题是否符合规范" + flag);
            if (!flag) {
                return ResultHelper.getResult(null, EnumAppCode.ERROR_READ_EXCEl, BaseResult.Status.ERROR,
                        "目标文件内容格式错误");
            }
            // 去除标题行
            list.remove(0);

            // 校验信息是否完整
            Map<String, List> map = checkListInfo(list);
            list = map.get("rightInfoList");
            int rightInfoNum = list.size();
            System.out.println("正确数据的表格列表" + list.toString());
            // 信息不完整行号
            List lackInfoRows = map.get("lackInfoRows");
            if (lackInfoRows.size() > 0 && null != lackInfoRows) {
                String lackInfoRowString = lackInfoRows.toString();
                String resultString = "{'lackInfoRows':" + lackInfoRowString + "}";
                Object resultJson = JSONObject.parse(resultString);
                return ResultHelper.getResult(null, EnumAppCode.PARAM_LACK, resultJson, "目标文件内容不完整");
            }
            // 新增失败行号
            List<Integer> insertErrorRows = new ArrayList<Integer>();
            // list中存的就是excel中的数据，可以根据excel中每一列的值转换成你所需要的值
            List<InfoWhiteListDto> whiteLists = addInfo2WhiteList(list);

            List<Integer> resultNum = (List<Integer>) whiteListConsumeService
                    .insertBatch(whiteLists, ((UserDto) request.getAttribute("currentUser")).getUserName())
                    .getResultList();
            System.out.println(resultNum.toString());
            // 处理结果集（车牌号重复行号数组）
            for (int i = 0; i < resultNum.size(); i++) {
                Integer insert = resultNum.get(i);
                ArrayList<String> rowList = list.get(i);
                if (insert > 0) {
                    String rowNum = rowList.get(6).substring((rowList.get(6).lastIndexOf("_") + 1));
                    insertErrorRows.add(Integer.valueOf(rowNum));
                }
            }
            String insertErrorRowsString = insertErrorRows.toString();
            String resultString = "{'successNum':" + (rightInfoNum - insertErrorRows.size()) + ",'insertErrorRows':"
                    + insertErrorRowsString + "}";
            Object resultJson = JSONObject.parse(resultString);
            ResultPojo result = ResultHelper.getResult(resultJson, "导入成功");
            return result;
        } catch (IOException e) {
            /*
             * RestResult result = new RestResult(BaseResult.Status.ERROR,
             * "批量导入异常"); result.addData(RestResult.OperatorType.CREATE,
             * EnumAppCode.ERROR_READ_EXCEl);
             */
            ResultPojo result = ResultHelper.getResult(e, EnumAppCode.ERROR_READ_EXCEl, BaseResult.Status.ERROR,
                    "批量导入异常");
            return result;
        } catch (Exception e) {
            ResultPojo result = ResultHelper.getResult(e, EnumAppCode.ERROR_READ_EXCEl, BaseResult.Status.ERROR,
                    "批量导入异常");
            /*
             * RestResult result = new RestResult(BaseResult.Status.ERROR,
             * "批量导入异常"); result.addData(RestResult.OperatorType.CREATE,
             * e.getMessage());
             */
            return result;
        }
    }

    /**
     * 完善白名单车辆的信息
     * 
     * @param list
     * @return
     */
    private List<InfoWhiteListDto> addInfo2WhiteList(List<ArrayList<String>> list) {
        List<InfoWhiteListDto> whiteLists = new ArrayList<>();
        // 处理excel转成的list
        for (ArrayList<String> arr : list) {
            ArrayList<String> rowList = arr;
            InfoWhiteListDto whiteList = new InfoWhiteListDto();
            // 第一列：车牌号码
            whiteList.setLicenseNumber(rowList.get(0));
            // 第二列：车牌类型
            String licenseTypeId = getLicenseTypeId(rowList.get(1));
            whiteList.setLicenseTypeId(licenseTypeId);
            whiteList.setLicenseTypeName(rowList.get(1));
            // 第三列：车辆类型
            String vehicleTypeId = getVehicleTypeId(rowList.get(2));
            whiteList.setVehicleTypeId(vehicleTypeId);
            whiteList.setVehicleTypeName(rowList.get(2));
            // 第四列：功能类型
            String funTypeId = getFunTypeId(rowList.get(3));
            whiteList.setFunTypeId(funTypeId);
            whiteList.setFunTypeName(rowList.get(3));
            // 第五列：所属单位
            whiteList.setVehicleDept(rowList.get(4));
            // 第六列：申请理由
            whiteList.setApplyReason(rowList.get(5));
            whiteLists.add(whiteList);
        }
        return whiteLists;
    }

    /**
     * 检验excel标题是否为模板文件格式
     * 
     * @param list
     * @return
     */
    private boolean checkTitle(List<ArrayList<String>> list) {
        boolean flag = true;
        ArrayList<String> excelTitle = list.get(0);
        flag = excelTitle.get(0).trim().equals("*车辆号牌") ? flag : false;
        flag = excelTitle.get(1).trim().equals("*车牌类型") ? flag : false;
        flag = excelTitle.get(2).trim().equals("*车辆类型") ? flag : false;
        flag = excelTitle.get(3).trim().equals("*功能类型") ? flag : false;
        flag = excelTitle.get(4).trim().equals("所属单位") ? flag : false;
        flag = excelTitle.get(5).trim().equals("信息备注") ? flag : false;
        return flag;
    }

    /**
     * 筛选不完整信息，返回信息完整的车辆列表，返回不完整的行数
     * 
     * @param list
     * @return
     */
    @SuppressWarnings("rawtypes")
    private Map<String, List> checkListInfo(List<ArrayList<String>> list) {
        Map<String, List> map = new HashMap<String, List>();
        List<ArrayList<String>> resultList = new ArrayList<ArrayList<String>>();
        // 信息不完整行号
        ArrayList<Integer> lackInfoRows = new ArrayList<Integer>();
        for (ArrayList<String> whiteListInfo : list) {
            if ((whiteListInfo.get(0).trim() != null && whiteListInfo.get(0).trim().length() > 0)
                    && (whiteListInfo.get(1).trim() != null && whiteListInfo.get(1).trim().length() > 0)
                    && (whiteListInfo.get(2).trim() != null && whiteListInfo.get(2).trim().length() > 0)
                    && (whiteListInfo.get(3).trim() != null && whiteListInfo.get(3).trim().length() > 0)) {
                resultList.add(whiteListInfo);
            } else {
                String rowNum = whiteListInfo.get(6);
                lackInfoRows.add(Integer.valueOf(rowNum.substring((rowNum.lastIndexOf("_")) + 1)));
            }
        }
        map.put("rightInfoList", resultList);
        map.put("lackInfoRows", lackInfoRows);
        return map;
    }

    /**
     * 对excel信息中空白行数进行筛选 设置行数数据
     * 
     * @param list
     * @return
     */
    private List<ArrayList<String>> deleteBlankRow(List<ArrayList<String>> list) {
        List<ArrayList<String>> resultList = new ArrayList<ArrayList<String>>();
        for (int i = 0; i < list.size(); i++) {
            // for (ArrayList<String> whiteListInfo : list) {
            ArrayList<String> whiteListInfo = list.get(i);
            if ((whiteListInfo.get(0).trim() != null && whiteListInfo.get(0).trim().length() > 0)
                    || (whiteListInfo.get(1).trim() != null && whiteListInfo.get(1).trim().length() > 0)
                    || (whiteListInfo.get(2).trim() != null && whiteListInfo.get(2).trim().length() > 0)
                    || (whiteListInfo.get(3).trim() != null && whiteListInfo.get(3).trim().length() > 0)) {
                // 增加行数设置
                whiteListInfo.add(6, "ROW_INDEX_" + (i + 1));
                resultList.add(whiteListInfo);
            }
        }
        return resultList;
    }

    /**
     * 获取车辆功能类型ID
     * 
     * @param funTypeId
     * @return
     */
    private String getFunTypeId(String funTypeName) {
        if ("公交客运".equals(funTypeName)) {
            return "VEHFUNTYPE01";
        } else if ("班车客运".equals(funTypeName)) {
            return "VEHFUNTYPE02";
        } else if ("洒水车".equals(funTypeName)) {
            return "VEHFUNTYPE03";
        } else if ("道路救援车".equals(funTypeName)) {
            return "VEHFUNTYPE04";
        } else if ("救护车".equals(funTypeName)) {
            return "VEHFUNTYPE05";
        } else if ("其它类型".equals(funTypeName)) {
            return "VEHFUNTYPE06";
        } else {
            return "VEHFUNTYPE06";
        }
    }

    /**
     * 获取车辆类型ID
     * 
     * @param string
     * @return
     */
    private String getVehicleTypeId(String vehicleTypeName) {
    	String vehicleTypeCode = "VEHSUBTYPE146";
    	List<VehicleDicDto> vehicleDicList =  UbmsDicServiceInvoke.vehicleDicListCommon;
    	if(vehicleDicList != null && vehicleDicList.size() >0) {
    		for(VehicleDicDto vehicleDic : vehicleDicList) {
        		if (vehicleTypeName.equals(vehicleDic.getDicName())) {
                    vehicleTypeCode = vehicleDic.getDicCode();
                    break;
                }
        	}
    	}
    	return vehicleTypeCode;
    }

    /**
     * 获取车牌类型id
     * 
     * @param licenseTypeId
     * @return
     */
    private String getLicenseTypeId(String licenseTypeName) {
        if ("白底黑字".equals(licenseTypeName)) {
            return "PLATECOLOR01";
        } else if ("蓝底白字".equals(licenseTypeName)) {
            return "PLATECOLOR02";
        } else if ("黄底黑字".equals(licenseTypeName)) {
            return "PLATECOLOR03";
        } else if ("黑底白字".equals(licenseTypeName)) {
            return "PLATECOLOR04";
        } else if ("绿底白字".equals(licenseTypeName)) {
            return "PLATECOLOR05";
        } else if ("其它颜色".equals(licenseTypeName)) {
            return "PLATECOLOR06";
        } else if ("白底红字".equals(licenseTypeName)) {
            return "PLATECOLOR07";
        } else {
            return "PLATECOLOR06";
        }
    }
}
